<?php
namespace app\admin\model\role;
use think\Model;
use app\admin\common;
use think\facade\Db;
class RolePermission extends Model {
	private $table_obj;
	
	public function selectRole($where,$field='*'){
		extract(common::get('role_permission',[$where,$field,__function__]));
		if(empty($data)){
			$admin=new RolePermission;
			$data=$admin::where($where)->field($field)->find()->toArray();
			common::set($data);
		}
		return $data;
	}
	
	public function selectMenuPermission($where,$field){
		extract(common::get('role_permission',[$where,$field,__function__]));
		if(empty($data)){
			$admin=new RolePermission;
			$data=$admin::where($where)->field($field)->select();
			if(isset($data)){
				common::set($data->toArray());
				return $data->toArray();
			}
			return [];
		}
		return $data;
	}
	/**
	 * 查找角色所拥有的菜单
	 * 
	 */
	public function selectRoleMenuPermission($where){
		extract(common::get('role_permission',[$where,__function__]));
		if(empty($data)){
			$data=Db::name('role_permission')
				->alias("p")	
				->field("m.function,m.status,m.id,p.menu_permission,p.role_id,p.menu_id,m.menu_name,m.pid,m.type")
			    ->join("menu m "," m.id=p.menu_id")
			    ->order("m.id asc")
			    ->where($where)
			    ->select();
			if(!empty($data)){
				common::set($data->toArray());
				return $data->toArray();
			}
			return [];   
		}
		return $data;  
		
	}
	/**
	 * 插入数据
	 * 
	 */
	public function insertAdminData($data){
		common::delete("role_permission");
		$admin=new RolePermission;
		$admin->save($data);
		return $admin->id;
	}
	/**
	 * 更新数据
	 */
	public function updateAdminData($up,$where){
		common::delete("role_permission");
		$admin=RolePermission::find($where);
		$r=$admin->save($up);
		return $r;
	}
	
	public function selectRoleData($where,$order,$limit){
		$data=RolePermission::where($where)->limit(current($limit),next($limit))->order($order)->select();
		return $data->toArray();
	}
	
	public function db_insert($data){
		common::delete("role_permission");
		return Db::name('role_permission')->strict(false)->insert($data);
	}
	
	public function db_update($up,$where){
		common::delete("role_permission");
		$result=Db::name('role_permission')
		    ->where($where)
		    ->update($up);
		return $result;    
	}
	
	public function insertAll($list){
		common::delete("role_permission");
		
		$RolePermission = new RolePermission;
		Db::startTrans();
		$r=Db::name('role_permission')->insertAll($list);
		if($r!=count($list)){
			Db::rollback();
			return false;
		}
		Db::commit();
		return true;
		
	}
	public function getSql(){
		return Db::name("role_permission")->getLastSql();
	}

}
?>